package VBox;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;

import Core.DB;

public class Job {
	Logger log = Logger.getAnonymousLogger();
	DB db = new DB();
	
	int add(String type, VM vm) {
		if(type.equalsIgnoreCase("START") == true) {
			String cmd="START "+vm.name;
			return addToDB(cmd);
		}
		
		if(type.equalsIgnoreCase("CREATE") == true) {
			String cmd="CREATE VMNAME OS RAM HDD CORES";
			cmd = cmd.replaceFirst("VMNAME", vm.name);
			cmd = cmd.replaceFirst("OS", vm.os.OSName);
			cmd = cmd.replaceFirst("RAM", vm.ram+"");
			cmd = cmd.replaceFirst("HDD", vm.hdd+"");
			cmd = cmd.replaceFirst("CORES", vm.cores+"");
			return addToDB(cmd);
		}
		
		if(type.equalsIgnoreCase("STOP") == true) {
			String cmd="STOP "+vm.name;
			return addToDB(cmd);
		}
		
		if(type.equalsIgnoreCase("MODIFY") == true) {
			String cmd="MODIFY VMNAME RAM HDD CORES";
			cmd = cmd.replaceFirst("VMNAME", vm.name);
			cmd = cmd.replaceFirst("RAM", vm.ram+"");
			cmd = cmd.replaceFirst("HDD", vm.hdd+"");
			cmd = cmd.replaceFirst("CORES", vm.cores+"");
			return addToDB(cmd);
		}
		if(type.equalsIgnoreCase("DELETE") == true) {
			String cmd="DELETE "+vm.name;
			return addToDB(cmd);
		}
		
		
		
		return 0;
	}
	
	
	int addToDB(String job) {
		
		try {
			Statement st;
			st = db.getCon().createStatement();
			String query = "INSERT INTO jobs(job) values ('"+job+"')"; 
			log.info("Executing : "+query);
			@SuppressWarnings("unused")
			int res = st.executeUpdate(query);
        
       log.info("Successfully added entry in DB");
       return 0;
	}
	catch (SQLException e) {
		log.severe("Error updating DB");
		log.severe(e.getMessage());
		
	}
	return -1;
	
	}

}